# -*- coding: UTF-8 -*-
# @Project ：VehicleDimensionMeasurementSystem 
# @File    ：app_function.py
# @IDE     ：PyCharm 
# @Date    ：2024/6/12 下午7:25
import json
import os
import shutil
from datetime import datetime

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QTableWidgetItem, QMessageBox
from loguru import logger

from source.utils.public_function import (QCheckBoxFiled, QTableWidgetFiled, QComboBoxFiled, QLineEditFiled,
                                          CompleteVehicleInfo, OverallDimensionsInspectionItem, WheelbaseInspectionItem,
                                          FenceInspectionItem, CurbWeighInspectionItem, CargoBoxInspectionItem,
                                          TankBodyInspectionItem)
from source.modules import app_settings
from source.modules.app_thread import WaitResponseResultQThread, WeighQThread
from source.utils.process_file import ProcessConfigParser
from source.database.db_operation import InsertData, VehicleRecordQuery
from source.utils.report_module import build_pdf


class AppFuncException(Exception):
    def __init__(self, message, status_code=None):
        super().__init__(message)
        self.status_code = status_code  # 状态码


class AppFunction:
    vehicle_info = None
    inspection_item_dict = None
    overall_dimensions_thread_state = False
    curb_weight_thread_state = False
    calculation_result_dict = {}
    overall_calculation_result_dict = {}
    insert_data_obj = InsertData()
    vehicle_query = VehicleRecordQuery()

    # 每次开始清空下对象和需要显示的内容
    @classmethod
    def empty_element(cls, widgets):
        """在开始流程中创建的一些对象或者显示的元素，进行下一个流程前应该进行清除，否则会产生干扰"""
        # 1. 清除表格中内容
        for row in range(1, widgets.tableWidgetCompleteVehicle.rowCount()):  # 从第二行开始
            for col in range(widgets.tableWidgetCompleteVehicle.columnCount()):  # 遍历所有列
                item = widgets.tableWidgetCompleteVehicle.item(row, col)
                if col == 0:
                    continue
                if item:  # 如果该位置有项，则清除它
                    item.setText("")  # 清除单元格文本

        # 2. 清除获取结果文件的线程
        widgets.wait_response_thread = None
        # 3. 清除获取检验项目的字典
        widgets.inspection_item_dict = None
        # 4. 清除称重等待的线程
        widgets.wait_weigh_thread = None
        # 5.清除线程执行的状态
        cls.overall_dimensions_thread_state = False
        cls.curb_weigh_thread_state = False
        # 6.清除检验记录ID
        cls.measure_record_id = None
        # # 7.打印按钮置为不可用
        widgets.btnPrintReport.setEnabled(False)

    # 获取检验项目
    @classmethod
    def get_inspection_item(cls, widgets):
        """获取检验项目"""
        item_dict = {
            'overall_dimensions': widgets.checkBoxOverallDimensions.isChecked(),
            'wheelbase': widgets.checkBoxWheelbase.isChecked(),
            'fence_depth': widgets.checkBoxFenceDepth.isChecked(),
            'curb_weigh': widgets.checkBoxCurbWeigh.isChecked(),
            'tank_body': widgets.checkBoxTankBody.isChecked(),
            'cargo_box': widgets.checkBoxCargoBox.isChecked(),
        }
        return {key: value for key, value in item_dict.items() if value}

    # 获取界面上的数据信息
    @classmethod
    def get_window_data(cls, widgets, inspection_item_list):
        """根据检验项目获取界面数据，单机操作需要"""
        plate_number = QComboBoxFiled(widgets.comboBoxPlateNumber, '号牌号码', 'plate_number')
        plate_type = QComboBoxFiled(widgets.comboBoxPlateType, '号牌种类', 'plate_type')
        vin = QLineEditFiled(widgets.levin, '车辆识别代号', 'vin')
        serial_number = QLineEditFiled(widgets.leSerialNumber, '流水号', 'serial_number')
        vehicle_type = QComboBoxFiled(widgets.comboBoxVehicleType, '车辆类型', 'vehicle_type')
        inspection_category = QComboBoxFiled(widgets.comboBoxInspectionClass, '检验类别', 'inspection_category')
        vehicle_class = QComboBoxFiled(widgets.comboBoxVehicleClass, '车辆所属类别', 'vehicle_class')
        vehicle_model = QLineEditFiled(widgets.leVehicleModel, '车辆型号', 'vehicle_model')
        total_mass = QLineEditFiled(widgets.leTotalMass, '总质量', 'total_mass')
        brand = QLineEditFiled(widgets.leBrand, '品牌', 'brand')
        body_color = QLineEditFiled(widgets.leBodyColor, '车身颜色', 'body_color')
        number_axes = QLineEditFiled(widgets.leAxleCountVehicle, '轴数', 'number_axes')
        vehicle_owner = QLineEditFiled(widgets.leVehicleOwner, '机动车所有人', 'vehicle_owner')
        date_first_registration = QLineEditFiled(widgets.leDateFirstRegistration, '初次登记日期',
                                                 'date_first_registration')
        manufacturer = QLineEditFiled(widgets.leManufacturer, '制造厂', 'manufacturer')
        # 基础信息
        basic_info = {'plate_number': plate_number, 'plate_type': plate_type, 'vin': vin,
                      'serial_number': serial_number, 'vehicle_type': vehicle_type,
                      'inspection_category': inspection_category, 'vehicle_class': vehicle_class,
                      'vehicle_model': vehicle_model, 'total_mass': total_mass, 'brand': brand,
                      'body_color': body_color, 'number_axes': number_axes, 'vehicle_owner': vehicle_owner,
                      'date_first_registration': date_first_registration, 'manufacturer': manufacturer}
        # 尺寸信息
        vehicle_size_info = {}
        # 根据检验项目来获取数据
        if 'overall_dimensions' in inspection_item_list:  # 外廓项目
            vehicle_standard_length = QTableWidgetFiled((0, 1), widgets.tableWidgetCompleteVehicle,
                                                        '标准长', 'vehicle_standard_length', )
            vehicle_size_info['vehicle_standard_length'] = vehicle_standard_length
            vehicle_standard_width = QTableWidgetFiled((0, 2), widgets.tableWidgetCompleteVehicle,
                                                       '标准宽', 'vehicle_standard_width', )
            vehicle_size_info['vehicle_standard_width'] = vehicle_standard_width
            vehicle_standard_height = QTableWidgetFiled((0, 3), widgets.tableWidgetCompleteVehicle,
                                                        '标准高', 'vehicle_standard_height', )
            vehicle_size_info['vehicle_standard_height'] = vehicle_standard_height
            # 获取限值
            limit_length = QLineEditFiled(widgets.leLimitLength, '长限值', 'limit_length')
            vehicle_size_info['limit_length'] = limit_length
            limit_width = QLineEditFiled(widgets.leLimitWidth, '宽限值', 'limit_width')
            vehicle_size_info['limit_width'] = limit_width
            limit_height = QLineEditFiled(widgets.leLimitHeight, '高限值', 'limit_height')
            vehicle_size_info['limit_height'] = limit_height
        if 'wheelbase' in inspection_item_list:
            vehicle_standard_wheelbase = QTableWidgetFiled((0, 4), widgets.tableWidgetCompleteVehicle,
                                                           '标准轴距', 'vehicle_standard_wheelbase', )
            vehicle_size_info['vehicle_standard_wheelbase'] = vehicle_standard_wheelbase
        if 'fence_depth' in inspection_item_list:
            vehicle_standard_fence_depth = QTableWidgetFiled((0, 5), widgets.tableWidgetCompleteVehicle,
                                                             '标准栏板深度', 'vehicle_standard_fence_depth', )
            vehicle_size_info['vehicle_standard_fence_depth'] = vehicle_standard_fence_depth
        if 'curb_weigh' in inspection_item_list:
            vehicle_standard_curb_weigh = QTableWidgetFiled((0, 6), widgets.tableWidgetCompleteVehicle,
                                                            '标准整备质量', 'vehicle_standard_curb_weigh', )
            vehicle_size_info['vehicle_standard_curb_weigh'] = vehicle_standard_curb_weigh
        if 'cargo_box' in inspection_item_list:
            cargo_hold_standard_length = QTableWidgetFiled((0, 7), widgets.tableWidgetCompleteVehicle,
                                                           '标准货箱长', 'cargo_hold_standard_length', )
            cargo_hold_standard_width = QTableWidgetFiled((0, 8), widgets.tableWidgetCompleteVehicle,
                                                          '标准货箱宽', 'cargo_hold_standard_width', )
            cargo_hold_standard_height = QTableWidgetFiled((0, 9), widgets.tableWidgetCompleteVehicle,
                                                           '标准货箱高', 'cargo_hold_standard_height', )
            vehicle_size_info['cargo_hold_standard_length'] = cargo_hold_standard_length
            vehicle_size_info['cargo_hold_standard_width'] = cargo_hold_standard_width
            vehicle_size_info['cargo_hold_standard_height'] = cargo_hold_standard_height
        if 'tank_body' in inspection_item_list:
            tank_standard_length = QTableWidgetFiled((0, 10), widgets.tableWidgetCompleteVehicle,
                                                     '罐体长', 'tank_standard_length', )
            tank_standard_width = QTableWidgetFiled((0, 11), widgets.tableWidgetCompleteVehicle,
                                                    '罐体宽', 'tank_standard_width', )
            tank_standard_height = QTableWidgetFiled((0, 12), widgets.tableWidgetCompleteVehicle,
                                                     '罐体高', 'tank_standard_height', )
            tank_standard_volume = QTableWidgetFiled((0, 13), widgets.tableWidgetCompleteVehicle,
                                                     '容积', 'tank_standard_volume', )
            tank_standard_angle = QTableWidgetFiled((0, 14), widgets.tableWidgetCompleteVehicle,
                                                    '安装角度', 'tank_standard_angle', )
            vehicle_size_info['tank_standard_length'] = tank_standard_length
            vehicle_size_info['tank_standard_width'] = tank_standard_width
            vehicle_size_info['tank_standard_height'] = tank_standard_height
            vehicle_size_info['tank_standard_volume'] = tank_standard_volume
            vehicle_size_info['tank_standard_angle'] = tank_standard_angle
        # 根据勾选不同的检测项目
        required_item_dict = {
            'overall_dimensions': [vehicle_size_info.get('vehicle_standard_length'),
                                   vehicle_size_info.get('vehicle_standard_width'),
                                   vehicle_size_info.get('vehicle_standard_height'), ],
            'wheelbase': vehicle_size_info.get('vehicle_standard_wheelbase'),
            'fence_depth': vehicle_size_info.get('vehicle_standard_fence_depth'),
            'curb_weigh': vehicle_size_info.get('vehicle_standard_curb_weigh'),
            'cargo_box': [vehicle_size_info.get('cargo_hold_standard_length'),
                          vehicle_size_info.get('cargo_hold_standard_width'),
                          vehicle_size_info.get('cargo_hold_standard_height'), ],
            'tank_body': [vehicle_size_info.get('tank_standard_length'),
                          vehicle_size_info.get('tank_standard_width'),
                          vehicle_size_info.get('tank_standard_height'), ],
        }
        # 创建一个车辆信息对象
        vehicle_info_object = CompleteVehicleInfo(**vehicle_size_info, **basic_info)
        # 往车辆对象中设置必须要填写的值
        for inspection_item in inspection_item_list:
            if inspection_item in required_item_dict:
                vehicle_info_object.add_not_null_item(required_item_dict.get(inspection_item))
        return vehicle_info_object

    # 开启外廓检验的线程
    @classmethod
    def start_overall_measure_thread(cls, widgets, vehicle_info: CompleteVehicleInfo):
        """开启外廓检测的线程"""
        plate_type = vehicle_info.plate_type.get_text  # 车辆类型
        only_trailer_model = widgets.checkBoxOnlyTrailerModel.isChecked()  # 获取单挂模式
        if only_trailer_model and plate_type == '15-挂车':
            measure_vehicle_mode = str(6)
        elif plate_type == '15-挂车':
            measure_vehicle_mode = str(1)
        else:
            measure_vehicle_mode = str(0)

        vehicle_type = vehicle_info.vehicle_type.get_text  # 获取车辆类型
        vehicle_model = vehicle_info.vehicle_model.get_text
        request_params = {'path': app_settings.REQUEST_FILE_NAME,
                          'trailer': measure_vehicle_mode,
                          'vehicle_type': vehicle_type,
                          'vehicle_model': vehicle_model if vehicle_model else '',
                          'history_mode': 1}
        config = ProcessConfigParser()
        config.build_request_ini(**request_params)
        logger.info(f'发送请求参数完成：{",".join([str({key: val}) for key, val in request_params.items()])}')
        cls.led_display(widgets,
                        message=f'{vehicle_info.plate_number.get_text}正在检测中...\n请保持车辆处于静止状态...')  # LED展示
        # 开启线程
        widgets.wait_response_thread = WaitResponseResultQThread()
        widgets.wait_response_thread.signal.connect(widgets.overall_thread_state)
        widgets.wait_response_thread.finished.connect(lambda: cls.thread_finished(widgets, 'overall_dimensions'))
        widgets.wait_response_thread.start()  # 开启线程

    # 开启整备质量检验的线程
    @classmethod
    def start_curb_weight_thread(cls, widgets, vehicle_info: CompleteVehicleInfo):
        """开启称重线程"""
        serial_port = widgets.comboBoxSerialPort.currentText()  # 串口
        baud_rate = widgets.comboBoxBaudRate.currentText()  # 波特率
        separator = widgets.comboBoxSeparator.currentText()  # 分隔符
        direction = widgets.comboBoxDirection.currentText()  # 方向
        stable_count = widgets.lesTableCount.text().strip()  # 稳定次数
        car_guide_weight = widgets.leCarGuideWeight.text().strip()  # 引车员重量
        widgets.wait_weigh_thread = WeighQThread(serial_port, baud_rate, direction, stable_count, car_guide_weight)
        widgets.wait_weigh_thread.weigh_signal.connect(widgets.weigh_thread_state)
        widgets.wait_weigh_thread.finished.connect(lambda: cls.thread_finished(widgets, 'curb_weigh'))  # 线程结束
        widgets.wait_weigh_thread.start()

    # 根据检验类别判定是否是新车
    @staticmethod
    def judge_is_new_vehicle(widgets):
        """根据检验类别判定是否新车"""
        inspection_category = widgets.comboBoxInspectionClass.currentText()
        if inspection_category == '00-注册登记安全检验':  # 新车
            judge_dict = app_settings.NEW_VEHICLE_STANDARD
        else:
            judge_dict = app_settings.OLD_VEHICLE_STANDARD  # 在用车
        return judge_dict

    # 处理外廓测量完后的结果
    @classmethod
    def process_overall_result(cls, widgets, result_dict, inspection_item_dict, vehicle_info: CompleteVehicleInfo):
        inspection_item_list = [key for key in inspection_item_dict.keys() if
                                key != 'curb_weigh']  # 除整备质量以外的项目
        judge_dict = cls.judge_is_new_vehicle(widgets)
        calculation_object = ShowCalculationResults(widgets, result_dict, vehicle_info, judge_dict)  # 创建对象
        inspection_item_class_dict = {
            'overall_dimensions': lambda: calculation_object.overall_calculate_func(),
            'wheelbase': lambda: calculation_object.wheelbase_calculate_func(),
            'fence_depth': lambda: calculation_object.fence_depth_calculate_func(),
            'cargo_box': lambda: calculation_object.cargo_box_calculate_func(),
            'tank_body': lambda: calculation_object.tank_calculate_func()
        }
        for inspection_item in inspection_item_list:
            inspection_item_class_dict.get(inspection_item)()  # 执行函数
        return calculation_object.get_calculation_result_dict()

    # 处理整备质量测量完成后的结果
    @classmethod
    def process_weight_result(cls, widgets, result_dict, vehicle_info: CompleteVehicleInfo):
        # 显示称重的重量
        widgets.lcdNumberWeight.display(result_dict.get('weight'))
        widgets.labelStableCount.setText(
            f'稳定次数：{result_dict.get("count")}/{result_dict.get("stable_count")}')
        if result_dict.get('state'):  # 表示称重已经完成计数
            weight_value = result_dict.get('weight')
            judge_dict = cls.judge_is_new_vehicle(widgets)
            # 判断是否是单挂，单挂模式不扣减引车员重量
            if widgets.inspection_item_dict.get('only_trailer_model', None):
                weigh_value = int(weight_value)
                logger.info(f'称重完成，重量为【未扣减引车员】：{weigh_value}千克')
            else:
                weigh_value = int(weight_value) - (0 or int(result_dict.get('car_guide_weight')))
                logger.info(f'称重完成，重量为【扣减引车员】：{weigh_value}千克')
            calculation_object = ShowCalculationResults(widgets, {}, vehicle_info, judge_dict)  # 创建对象
            calculation_object.curb_weigh_calculate_func(weigh_value)
            return calculation_object.get_calculation_result_dict()

    # 当线程结束后执行操作（外廓和整备质量）
    @classmethod
    def thread_finished(cls, widgets, thread_name):
        if thread_name == 'overall_dimensions':
            cls.overall_dimensions_thread_state = True
            cls.show_operation_info(widgets=widgets, message='外廓检测已完成')
            cls.led_display(widgets, message='外廓项目检测完成')
            cls.calculation_result_dict.update(widgets.overall_calculated_result_dict)
        if thread_name == 'curb_weigh':
            cls.curb_weight_thread_state = True
            cls.show_operation_info(widgets=widgets, message='重量检测已完成')
            cls.led_display(widgets, message='称重项目检测完成')
            cls.calculation_result_dict.update(widgets.weigh_calculated_result_dict)
        db_result_dict = cls.process_overall_or_weight(cls.inspection_item_dict, cls.vehicle_info)
        if not db_result_dict:
            return
        serial_number = cls.vehicle_info.serial_number.get_text  # 流水号
        inspection_category = cls.vehicle_info.inspection_category.get_text  # 检验类别
        # 将数据插入到数据库中
        measure_record_id = cls.insert_data_obj.insert_measure_record(serial_number, db_result_dict,
                                                                      inspection_category)
        widgets.measure_record_id = measure_record_id  # 设置当前检验记录的id到窗口对象中，方便调用
        widgets.btnPrintReport.setEnabled(True)  # 激活报告单可以打印状态
        total_judge = db_result_dict.get("total_judge")
        cls.led_display(widgets, message=f'检验结论：{"合格" if total_judge else "不合格"}')

    @classmethod
    def build_overall_correlation_dict(cls, inspection_item_dict, calculation_result_dict):
        """构建外廓相关的字典"""
        overall_db_data = {}
        for inspection_item in inspection_item_dict.keys():
            calculation_list = calculation_result_dict.get(inspection_item)  # 获取到的是
            if inspection_item == 'overall_dimensions':  # 外廓项目
                overall_db_data['measure_length'] = calculation_list[0][1]  # 测量长
                overall_db_data['measure_width'] = calculation_list[1][1]  # 测量宽
                overall_db_data['measure_height'] = calculation_list[2][1]  # 测量高
                overall_db_data['length_diff'] = calculation_list[0][2]  # 长差值
                overall_db_data['width_diff'] = calculation_list[1][2]  # 宽差值
                overall_db_data['height_diff'] = calculation_list[2][2]  # 高差值
                overall_db_data['length_per'] = calculation_list[0][3]  # 长差值百分比
                overall_db_data['width_per'] = calculation_list[1][3]  # 宽差值百分比
                overall_db_data['height_per'] = calculation_list[2][3]  # 高差值百分比
                overall_db_data['length_judge'] = calculation_list[0][4]  # 长判定
                overall_db_data['width_judge'] = calculation_list[1][4]  # 宽判定
                overall_db_data['height_judge'] = calculation_list[2][4]  # 高判定
            elif inspection_item == 'wheelbase':
                overall_db_data['measure_wheelbase'] = calculation_list[0][1]
                overall_db_data['wheelbase_diff'] = calculation_list[0][2]  # 轴距差值
                overall_db_data['wheelbase_per'] = calculation_list[0][3]  # 轴距差值百分比
                overall_db_data['wheelbase_judge'] = True if calculation_list[0][4] == '合格' else False
            elif inspection_item == 'fence_depth':
                overall_db_data['measure_fence_depth'] = calculation_list[0][1]
                overall_db_data['fence_depth_diff'] = calculation_list[0][2]  # 栏板深度差值
                overall_db_data['fence_depth_per'] = calculation_list[0][3]  # 栏板深度差值百分比
                overall_db_data['fence_depth_judge'] = True if calculation_list[0][4] == '合格' else False
            elif inspection_item == 'curb_weigh':
                overall_db_data['measure_curb_weigh'] = calculation_list[0][1]
                overall_db_data['curb_weigh_diff'] = calculation_list[0][2]  # 整备质量差值
                overall_db_data['curb_weigh_per'] = calculation_list[0][3]  # 整备质量百分比
                overall_db_data['curb_weigh_judge'] = True if calculation_list[0][4] == '合格' else False
        return overall_db_data

    # 构建一个需要存入数据库的字典
    @classmethod
    def process_overall_or_weight(cls, inspection_item_dict, vehicle_info):
        """处理检测外廓和称重的数据"""
        is_item = any([item in cls.inspection_item_dict for item in
                       ['overall_dimensions', 'wheelbase', 'fence_depth', 'tank_body', 'cargo_box']])

        # 情况1是只测外廓测情况
        if is_item and 'curb_weigh' not in inspection_item_dict:  # 说明只有外廓项目
            if cls.overall_dimensions_thread_state:
                db_result_dict = cls.build_overall_correlation_dict(inspection_item_dict, cls.calculation_result_dict)
            else:
                db_result_dict = {}
        elif not is_item and 'curb_weigh' in inspection_item_dict:  # 说明只有整备项目
            if cls.curb_weight_thread_state:
                db_result_dict = cls.build_overall_correlation_dict(inspection_item_dict, cls.calculation_result_dict)
            else:
                db_result_dict = {}
        elif is_item and 'curb_weigh' in inspection_item_dict:
            if cls.overall_dimensions_thread_state and cls.curb_weight_thread_state:
                db_result_dict = cls.build_overall_correlation_dict(inspection_item_dict, cls.calculation_result_dict)
            else:
                db_result_dict = {}
        else:
            db_result_dict = {}
        # 执行完成后对存入数据库的数据进行处理
        if db_result_dict:
            total_judge = all(value for value in db_result_dict.values())  # 总判定
            db_result_dict['total_judge'] = total_judge
            db_result_dict['measure_time'] = datetime.now()
            # 保存图片操作
            serial_number = vehicle_info.serial_number.get_text
            picture_path_dict = {
                'head_picture_path': [f'{app_settings.PICTURE_DIR}/{serial_number}_head.jpg', 1],
                'after_picture_path': [f'{app_settings.PICTURE_DIR}/{serial_number}_after.jpg', 2],
                'side_picture_path': [f'{app_settings.PICTURE_DIR}/{serial_number}_side.jpg', 3],
                'top_picture_path': [f'{app_settings.PICTURE_DIR}/{serial_number}_top.jpg', 4]
            }

            for key, value in picture_path_dict.items():
                source_image_path = os.path.join(app_settings.MESSAGE_DIR, f'{value[1]}.jpg')
                cls.copy_image_to_dir(source_image_path, value[0])

            db_result_dict['picture_path'] = json.dumps(picture_path_dict, ensure_ascii=False)
        return db_result_dict

    # 在界面文本框展示日志信息，需要调用触发
    @classmethod
    def show_operation_info(cls, widgets, message):
        """在文本框展示操作日志"""
        widgets.textEditLog.append(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}::{message}")

    # LED的屏展示
    @staticmethod
    def led_display(widgets, message):
        widgets.labelLEDDisplay.setText(f'{message}')  # LED展示

    # 复制图片到指定目录，有重复会自动替换
    @staticmethod
    def copy_image_to_dir(source_image_path, target_path):
        """复制图片到指定目录下"""
        if not os.path.exists(source_image_path):
            raise FileNotFoundError
        shutil.copy2(source_image_path, target_path)

    # 打印报告单
    @classmethod
    def print_report(cls, measure_record_id):
        # """执行打印报告单"""
        if not measure_record_id:
            raise AppFuncException(status_code=5000, message='未产生检验记录，无法打印相关类型')
        measure_record, vehicle_info = cls.vehicle_query.query_measure_record(measure_record_id)
        serial_number = vehicle_info.serial_number
        pdf_name = os.path.join(app_settings.PICTURE_DIR, f'{serial_number}.pdf')
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        build_pdf(vehicle_info, measure_record, pdf_name)  # 生成PDF
        if os.name == 'nt':  # windows的操作
            os.startfile(pdf_name)

    # 单机或联网测试一个流程
    @classmethod
    def alon_networking_mode(cls, mode, widgets):
        if mode == 'stand_alone_mode':
            cls.empty_element(widgets)  # 清空状态
            cls.inspection_item_dict = cls.get_inspection_item(widgets)  # 检验项目
            if not cls.inspection_item_dict:
                QMessageBox.warning(widgets, '系统提示', '请选择检验项目')
                return
            widgets.inspection_item_dict = cls.inspection_item_dict
            cls.vehicle_info = cls.get_window_data(widgets, cls.inspection_item_dict)
            # 去判断是否有必填的项目需要填写
            required_items = [item for item in cls.vehicle_info.detection_required_item()]  # 获取需要检测的必填项
            # 检查是否有未填写的必填项
            if any(required_items):
                # 弹出警告框
                [QMessageBox.warning(widgets, '系统提示', f'{item.get("filed_title")}不能为空') for item in
                 required_items]
                return
            logger.info('创建车辆对象完成！')
            widgets.vehicle_info_object = cls.vehicle_info
            cls.insert_data_obj.insert_vehicle_info(cls.vehicle_info)  # 将车辆信息写入数据库
            if any([item in cls.inspection_item_dict for item in
                    ['overall_dimensions', 'wheelbase', 'fence_depth', 'tank_body', 'cargo_box']]):  # 有外廓项目
                cls.start_overall_measure_thread(widgets, cls.vehicle_info)
            if 'curb_weigh' in cls.inspection_item_dict:
                """是否有称重检验项目"""
                cls.start_curb_weight_thread(widgets, cls.vehicle_info)


class ShowCalculationResults:
    """用于展示计算结果"""

    def __init__(self, ui, result_dict, vehicle_info_object, judge_dict):
        self.ui = ui
        self.result_dict = result_dict
        self.vehicle_info_object = vehicle_info_object
        self.judge_dict = judge_dict
        self.calculation_result_dict = {}

    @staticmethod
    def replace_status(tuples):
        result = []
        for item in tuples:
            if not item[-1]:
                result.append(item[:-1] + ('不合格',))
            else:
                result.append(item[:-1] + ('合格',))
        return result

    def list_data_show_table(self, overall_result_list, start_column):
        """将列表数据展示到表格中"""
        result_list = self.replace_status(overall_result_list)
        # 执行展示到界面上
        for column, data_tuple in enumerate(result_list):
            for row, item in enumerate(data_tuple[1:]):
                if data_tuple[-1] == '不合格':
                    self.ui.tableWidgetCompleteVehicle.setItem(row + 1, column + start_column,
                                                               QTableWidgetItem(str(item)))
                    self.ui.tableWidgetCompleteVehicle.item(row + 1, column + start_column).setForeground(
                        Qt.GlobalColor.red)
                else:
                    self.ui.tableWidgetCompleteVehicle.setItem(row + 1, column + start_column,
                                                               QTableWidgetItem(str(item)))
                    self.ui.tableWidgetCompleteVehicle.item(row + 1, column + start_column).setForeground(
                        Qt.GlobalColor.green)

    def overall_calculate_func(self):
        """外廓计算结果并展示到页面"""
        result_overall = [int(self.result_dict.get('length')), int(self.result_dict.get('width')),
                          int(self.result_dict.get('height'))]
        # 获取标准数据
        standard_overall = [
            int(self.vehicle_info_object.vehicle_standard_length.get_text),
            int(self.vehicle_info_object.vehicle_standard_width.get_text),
            int(self.vehicle_info_object.vehicle_standard_height.get_text)]
        judge_overall = [self.judge_dict.get('length'), self.judge_dict.get('width'), self.judge_dict.get('height')]
        # 获取限值
        limit_length = self.ui.leLimitLength.text().strip()
        limit_width = self.ui.leLimitWidth.text().strip()
        limit_height = self.ui.leLimitHeight.text().strip()
        if limit_length == '' and limit_width == '' and limit_height == '':
            limit_overall = None
        else:
            limit_overall = [int(limit_length), int(limit_width), int(limit_height)]
        # 创建一个判定对象
        overall_item_obj = OverallDimensionsInspectionItem(limit_overall, result_overall,
                                                           standard_overall, judge_overall)
        # 执行计算返回一个结果
        overall_result_list = overall_item_obj.integrate_result()
        self.calculation_result_dict['overall_dimensions'] = overall_result_list  # 将结果添加到字典中
        # 处理下列表
        result_list = self.replace_status(overall_result_list)
        # 执行展示到界面上
        for column, data_tuple in enumerate(result_list):
            for row, item in enumerate(data_tuple[1:]):
                current_item = QTableWidgetItem(str(item))
                current_item.setTextAlignment(Qt.AlignCenter)  # 设置左右居中对齐
                if data_tuple[-1] == '不合格':
                    self.ui.tableWidgetCompleteVehicle.setItem(row + 1, column + 1, current_item)
                    self.ui.tableWidgetCompleteVehicle.item(row + 1, column + 1).setForeground(
                        Qt.GlobalColor.red)
                else:
                    self.ui.tableWidgetCompleteVehicle.setItem(row + 1, column + 1, current_item)
                    self.ui.tableWidgetCompleteVehicle.item(row + 1, column + 1).setForeground(
                        Qt.GlobalColor.green)

    def public_calculate_func(self, result_value, inspection_, inspection_class, table_widget, column):
        """一个用于公共计算的函数"""
        standard_value = getattr(self.vehicle_info_object, f'vehicle_standard_{inspection_}').get_text
        judge_value = self.judge_dict.get(inspection_)
        item_object = inspection_class(int(result_value), int(standard_value), judge_value)
        lst = item_object.integrate_result()
        result_list = self.replace_status(lst)
        self.calculation_result_dict[inspection_] = result_list
        for row, item in enumerate(result_list[0][1:]):
            current_item = QTableWidgetItem(str(item))
            current_item.setTextAlignment(Qt.AlignCenter)  # 设置左右居中对齐
            if result_list[0][-1] == '不合格':
                table_widget.setItem(row + 1, column, current_item)
                table_widget.item(row + 1, column).setForeground(
                    Qt.GlobalColor.red)
            else:
                table_widget.setItem(row + 1, column, current_item)
                table_widget.item(row + 1, column).setForeground(
                    Qt.GlobalColor.green)

    def wheelbase_calculate_func(self):
        """轴距的计算与展示"""
        wheelbase_result = self.result_dict.get('wheelbase')
        self.public_calculate_func(wheelbase_result, 'wheelbase', WheelbaseInspectionItem,
                                   self.ui.tableWidgetCompleteVehicle, 4)

    def fence_depth_calculate_func(self):
        """栏板深度"""
        fence_depth_result = self.result_dict.get('hxheight')
        self.public_calculate_func(fence_depth_result, 'fence_depth', FenceInspectionItem,
                                   self.ui.tableWidgetCompleteVehicle, 5)

    def curb_weigh_calculate_func(self, curb_weigh):
        """整备质量"""
        self.public_calculate_func(curb_weigh, 'curb_weigh', CurbWeighInspectionItem,
                                   self.ui.tableWidgetCompleteVehicle, 6)

    def cargo_box_calculate_func(self):
        """计算货箱尺寸"""
        measure_cargo_hold_length = self.result_dict.get('hxinnerlen')
        measure_cargo_hold_width = self.result_dict.get('hxinnerwid')
        measure_cargo_hold_height = self.result_dict.get('hxinnerhei')

        measure_results = [int(measure_cargo_hold_length), int(measure_cargo_hold_width),
                           int(measure_cargo_hold_height)]
        # 获取标准数据
        standard_values = [
            int(self.vehicle_info_object.cargo_hold_standard_length.get_text),
            int(self.vehicle_info_object.cargo_hold_standard_width.get_text),
            int(self.vehicle_info_object.cargo_hold_standard_height.get_text)]
        judge_tolerances = [self.judge_dict.get('cargo_hold_length'), self.judge_dict.get('cargo_hold_width'),
                            self.judge_dict.get('cargo_hold_height')]
        # 创建一个判定对象
        cargo_box_item_obj = CargoBoxInspectionItem(measure_results, standard_values, judge_tolerances)
        # 执行计算返回一个结果
        tank_result_list = cargo_box_item_obj.integrate_result()
        self.calculation_result_dict['cargo_box'] = tank_result_list  # 将结果添加到字典中
        self.list_data_show_table(tank_result_list, 7)

    def tank_calculate_func(self):
        """用于罐体相关信息的展示"""
        measure_tank_length = self.result_dict.get('tanklength', 0)
        measure_tank_width = self.result_dict.get('tankwidth', 0)
        measure_tank_height = self.result_dict.get('tankheight', 0)
        measure_tank_volume = self.result_dict.get('tankvol', 0)
        measure_tank_angle = self.result_dict.get('angle', 0)
        measure_results = [int(measure_tank_length), int(measure_tank_width),
                           int(measure_tank_height), float(measure_tank_volume), float(measure_tank_angle)]
        standard_values = [
            int(self.vehicle_info_object.tank_standard_length.get_text),
            int(self.vehicle_info_object.tank_standard_width.get_text),
            int(self.vehicle_info_object.tank_standard_height.get_text),
            float(self.vehicle_info_object.tank_standard_volume.get_text),
            float(self.vehicle_info_object.tank_standard_angle.get_text)
        ]
        judge_tolerances = [self.judge_dict.get('cargo_hold_length'), self.judge_dict.get('cargo_hold_width'),
                            self.judge_dict.get('cargo_hold_height'), self.judge_dict.get('tank_volume'),
                            self.judge_dict.get('tank_angle')]
        tank_item_obj = TankBodyInspectionItem(measure_results, standard_values, judge_tolerances)
        tank_result_list = tank_item_obj.integrate_result()
        self.calculation_result_dict['tank_body'] = tank_result_list
        self.list_data_show_table(tank_result_list, 10)

    def get_calculation_result_dict(self):
        """获取测量结果的字典"""
        return self.calculation_result_dict
